package com.software.loginregister.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.software.loginregister.R;
import com.software.loginregister.activity.RecommendDetailActivity;
import com.software.loginregister.databasesHelper.WorksDao;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.WorksDTO;
import com.software.loginregister.entity.vo.WorksListVO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecommendAdapter extends RecyclerView.Adapter<RecommendAdapter.RecipeViewHolder> {
    private Context context;
    private List<WorksDTO> worksList;

    public RecommendAdapter(Context context, List<WorksDTO> worksList) {
        this.context = context;
        this.worksList = worksList;
    }

    @NonNull
    @Override
    public RecipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_recommend, parent, false);
        return new RecipeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecipeViewHolder holder, int position) {
        WorksDTO works = worksList.get(position);
        String photoUrl = works.getPhotoUrl();
        Log.d("RecommendAdapter", "Loading image for position " + position +
                ", photoUrl: " + photoUrl);

        // 设置数据
        holder.tvWorkName.setText(works.getWorksName());
        holder.tvUserName.setText(works.getNickname());
        holder.tvDifficulty.setText(works.getDifficulty ());
        holder.tvMainIngredients.setText(works.getIngredients());
        holder.tvLikeCount.setText(String.valueOf(works.getLikeCount()));


        // TODO: 使用图片加载库（如Glide）加载图片
        // 使用Glide加载图片
        Glide.with(context)
                .load(works.getPhotoUrl())
                .placeholder(R.drawable.image_loading) // 加载占位图
                .error(R.drawable.image_loading) // 加载错误图
                .diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存策略
                .centerCrop() // 图片填充方式
                .into(holder.ivWork);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            // 记录浏览历史
            recordBrowsingHistory(works.getWorksId());

            // 创建Intent
            Intent intent = new Intent(context, RecommendDetailActivity.class);
            Long worksId = Long.valueOf(works.getWorksId());
            Integer userId = works.getUserId();

            // 传递必要的数据
            if (worksId != null) {
                intent.putExtra("worksId", worksId.longValue());
            }
            if (userId != null) {
                intent.putExtra("userId", userId);
                Log.d("RecommendAdapter", "传递的userId: " + userId);
            } else {
                Log.e("RecommendAdapter", "userId为空，原始数据: " + works.toString());
            }
            intent.putExtra("worksName", works.getWorksName());
            intent.putExtra("nickname", works.getNickname());
            intent.putExtra("photoUrl", works.getPhotoUrl());
            intent.putExtra("difficulty", works.getDifficulty());
            intent.putExtra("likeCount", works.getLikeCount());
            intent.putExtra("avatar",works.getAvatar());
            intent.putExtra("description",works.getDescription());
            Log.d("RecommendDetailActivityDebug", "adapter传输作品id:"+works.getWorksId());
            Log.d("RecommendDetailActivityDebug", "adapter传输图片:"+works.getPhotoUrl());
            Log.d("RecommendDetailActivityDebug", "adapter传输userid:"+works.getUserId());


            context.startActivity(intent);
        });
    }


    @Override
    public int getItemCount() {
        return worksList != null ? worksList.size() : 0;
    }


    private void recordBrowsingHistory(Integer worksId) {
        Long userId = getUserId();
        if (userId == null || worksId == null) {
            Log.w("RecommendAdapter", "用户ID或作品ID为空，无法记录浏览历史");
            return;
        }

        RetrofitClient.getInstance()
                .getWorksApi()
                .recordBrowsingHistory(userId, worksId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                            Log.d("RecommendAdapter", "浏览历史记录成功");
                        } else {
                            Log.e("RecommendAdapter", "浏览历史记录失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Log.e("RecommendAdapter", "浏览历史记录网络请求失败", t);
                    }
                });
    }

    private Long getUserId() {
        try {
            return SharedPreferencesUtil.getUserInfo(context).getUserId();
        } catch (Exception e) {
            Log.e("RecommendAdapter", "获取用户ID失败", e);
            return null;
        }
    }

    static class RecipeViewHolder extends RecyclerView.ViewHolder {
        ImageView ivWork;
        TextView tvWorkName;
        TextView tvMainIngredients;
        TextView tvUserName;
        TextView tvDifficulty;
        TextView tvViewCount;
        TextView tvLikeCount;

        public RecipeViewHolder(@NonNull View itemView) {
            super(itemView);
            ivWork = itemView.findViewById(R.id.iv_work);
            tvWorkName = itemView.findViewById(R.id.tv_work_name);
            tvMainIngredients = itemView.findViewById(R.id.tv_main_ingredients);
            tvUserName = itemView.findViewById(R.id.tv_user_name);
            tvViewCount = itemView.findViewById(R.id.tv_view_count);
            tvDifficulty = itemView.findViewById(R.id.tv_difficulty);
            tvLikeCount = itemView.findViewById(R.id.tv_like_count);
        }
    }
}